package com.gulimall.ware.service.impl;

import com.gulimall.common.constant.WareConstant;
import com.gulimall.ware.entity.PurchaseDetailEntity;
import com.gulimall.ware.service.PurchaseDetailService;
import com.gulimall.ware.service.WareSkuService;
import com.gulimall.ware.vo.MergeVo;
import com.gulimall.ware.vo.PurchaseDoneVo;
import com.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.ware.dao.PurchaseDao;
import com.gulimall.ware.entity.PurchaseEntity;
import com.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private WareSkuService wareSkuService;
    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单（新建状态或已分配状态）的采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<PurchaseEntity>(){{
            eq("status", WareConstant.PurchaseStatusEnum.NEWCREATE.getCode())
                    .or()
                    .eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        }};

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购需求接口
     * 1、先判断采购单id是否为空
     * 1.1、为空->需要新建采购单
     * 1.2、不为空 ->将采购需求合并到该采购单上
     * 1.2.1、判断状态是否是新建或已分配状态 ，其他的状态不允许进行合并操作
     * 2、批量修改采购需求的状态、采购需求的采购单id
     * 3、更新采购单的最后修改时间
     * @param mergeVo
     */
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        //1、判断采购单id是否为空
        if (mergeVo.getPurchaseId() == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.NEWCREATE.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);

            //将新建的采购单id赋值到mergeVo的purchaseId中
            mergeVo.setPurchaseId(purchaseEntity.getId());
        }

        //获取采购需求id集合
        List<Long> items = mergeVo.getItems();

        //以流的方式收集数据
        List<PurchaseDetailEntity> purchaseDetailEntityList = items.stream().filter(item->{
            //过滤掉采购需求的状态为新建或已分配之外的数据
            PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item);
            if (purchaseDetail.getStatus() == WareConstant.PurchaseDetailStatusEnum.NEWCREATE.getCode() ||
            purchaseDetail.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(mergeVo.purchaseId);
            //采购单状态修改为已分配
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());

            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        //2、修改采购需求（状态、采购单id）
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);

        ///3、采购需求更新后将采购单的修改时间以及采购总金额进行更新
        //用于汇总本次采购项的总金额
        BigDecimal total = new BigDecimal(0);
        //统计本次采购的总金额
        for (PurchaseDetailEntity purchaseDetailEntity : purchaseDetailEntityList) {
            PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(purchaseDetailEntity.getId());
            total = total.add(purchaseDetail.getSkuPrice());
        }
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(mergeVo.getPurchaseId());
        purchaseEntity.setAmount(total);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * 领取采购单接口
     * 1、确认当前所有采购单的状态是否为新建或已领取
     * 2、修改采购单状态为 已领取
     * 3、修改当前采购的所有采购需求为 正在采购
     * @param ids 采购单id集合
     */
    @Transactional
    @Override
    public void receivedPurchase(List<Long> ids) {
        //1、确认当前所有采购单的状态是否为新建或已分配
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(id -> {
            PurchaseEntity purchase = this.getById(id);
            return purchase;
        }).filter(purchase -> {
            //过滤掉状态不是新建或已分配的采购单
            if (purchase.getStatus() == WareConstant.PurchaseStatusEnum.NEWCREATE.getCode() ||
                    purchase.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(purchase->{
            //将收集到的采购单的状态修改为已领取状态
            purchase.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            //采购单修改时间为当前时间
            purchase.setUpdateTime(new Date());
            return purchase;
        }).collect(Collectors.toList());

        //2、修改采购单状态以及更新时间
        this.updateBatchById(purchaseEntityList);

        //3、修改当前采购的所有采购需求为 正在采购
        for (PurchaseEntity purchase : purchaseEntityList) {
            //获取所有该采购单下的采购项
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.listDetailByPurchaseId(purchase.getId());

            //以流的形式重新收集要修改的数据
            List<PurchaseDetailEntity> collect = purchaseDetailEntityList.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item.getId());
                //将采购需求改为正在采购
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.PURCHASING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect);
        }
    }

    /**
     * 完成采购单接口
     * 1、改变采购单状态 （根据采购项而定，采购项全部完成->采购单完成 ，采购项有失败->采购单有异常）
     * 2、改变采购项状态
     * 3、将成功采购的进行入库
     * @param doneVo
     */
    @Transactional
    @Override
    public void donePurchase(PurchaseDoneVo doneVo) {
        //2、改变采购项状态
        Boolean flag = true;
        //获取所有用户提交采购的采购项
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        //创建一个要进行批量修改的采购项集合
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        //遍历所有的采购项，查看是否有采购失败的
        for (PurchaseItemDoneVo item : items) {
            //如果有失败的采购需求，将flag改为false
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.FAILED.getCode()) {
                flag = false;
            }else {
                //3、将成功采购的采购项进行入库
                PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item.getItemId());
                //传三个值（skuId ,仓库id，入库数量）
                wareSkuService.addStock(purchaseDetail.getSkuId(),purchaseDetail.getWareId(),purchaseDetail.getSkuNum());
            }

            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setStatus(item.getStatus());
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updates);

        //1、改变采购单状态 （根据采购项而定，采购项全部完成->采购单完成 ，采购项有失败->采购单有异常）
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        //状态： 如果flag的值为TRUE则为已完成，为false则为有异常
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISHED.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}